<template>
  <div id="canvas-box">
    <canvas
      id="myCanvas"
      width="1200"
      height="800"
      style="border:1px solid #000000;"
    ></canvas>
  </div>

</template>

<script>
export default {
  data () {
    return {
      c: {},
      ctx: {}
    }
  },
  mounted () {
    this.c = document.getElementById('myCanvas')
    this.ctx = this.c.getContext('2d')
    this.initEvent()
  },
  methods: {
    initEvent () {
      var line = {
        x: 0,
        y: 0
      }
      var draw = false
      var item = []
      const that = this
      that.c.addEventListener('mousedown', function (e) {
        line.x = e.offsetX
        line.y = e.offsetY
        draw = true
        item = []
      })
      document.addEventListener('mouseup', function (e) {
        line.x = e.offsetX
        line.y = e.offsetY
        draw = false
        that.$socket.emit('strokes_in', item)
      })
      this.c.addEventListener('mousemove', function (e) {
        if (draw) {
          that.ctx.moveTo(line.x, line.y)
          that.ctx.lineTo(e.offsetX, e.offsetY)
          that.ctx.stroke()
          line.x = e.offsetX
          line.y = e.offsetY
          item.push(JSON.parse(JSON.stringify(line)))
        }
      })
    }
  },
  sockets: {
    strokes_out (data) {
      let that = this
      for (let i = 0; i < data.data.length - 1; i++) {
        that.ctx.moveTo(data.data[i].x, data.data[i].y)
        that.ctx.lineTo(data.data[i + 1].x, data.data[i + 1].y)
        that.ctx.stroke()
      }
    }
  }
}
</script>

<style scope>
</style>
